package com.task.controller;

import com.task.config.WeChatConfig;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * @author jiafujun
 * 2020年01月21日 09:43:00
 */
@Slf4j
@Controller
@RequestMapping("/weChat")
public class WeChatController {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private WeChatConfig weChatConfig;

    @RequestMapping("/auth")
    public String authorize() {
        String url = "http://2u7661862c.qicp.vip/weChat/userInfo";
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, "123");
        log.info("微信网页授权:获取code,redirectURL={}", redirectUrl);

        return "redirect:" + redirectUrl;
    }


    @RequestMapping("/userInfo")
    public String userinfo(@RequestParam("code") String code, String state) {
        log.info("微信网页授权: code={}", code);
        log.info("微信网页授权: state={}", state);    //即authorize中的returnUrl
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        WxMpUser userInfo;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);

            userInfo = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        } catch (WxErrorException e) {
            log.info("微信网页授权: {}", e);
            return e.getError().getErrorMsg();
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("微信网页授权: openId={}", openId);
        log.info("微信网页授权: openId={}", userInfo.toString());

        return "redirect:/page/task";
    }
}
